//****************************************************************
//  pinyinizerOverlay.js
//	Written by: Benny Wong (bdotdub at gmail.com)
//
//  This file will basically grab the selected text, put it in the
//  right click menu, and then open it in a new tab if chosen.
//
//  TODO:
//  - New window depending on setting
//
//***************************************************************

//---
// Variables
//---
var xrequest = new XMLHttpRequest();
// Get the "pinyinizer." branch
function init() {
    var focusedWindow = document.commandDispatcher.focusedWindow;
    var text = focusedWindow.getSelection();

    if(text=='') {
    }
    else{
	try {  // get the pref
	    var url = 'http://www.pin1yin1.com/?q=popup&v=1.1&t='+escape(text);
		xrequest.onload = parseContent;
	    	xrequest.open("GET",url,true);
	    	xrequest.send(null);
	}
	catch(e) {  // if pref doesnt exist, create it
	    if (confirm("First Time Use:\n\n     Press OK to: Open in the sidebar\n     Press Cancel to: Open in a new tab\n\nYou can always change your preference in the options menu."))
		prefs.setCharPref('view', 'sidebar');
	    else
		prefs.setCharPref('view', 'newtab');
	    pinyinizer();
	}
    }
}


//-------------------
// parseContent() - gets the response and creates a floating/draggable 
//	div that will contain the pinyin
//------------------
function parseContent() {
   var result = xrequest.responseText;
   var str = "";
   var str = new String(result);
   tabs = str.match(/<td>([^>]*)<\/td>/g);

   var str = "";
   for (var x = 0; x < tabs.length; x = x + 1)
   {
	str = str + tabs[x].substring(4, tabs[x].length-5) + " ";
   }

document.getElementById('pinyinizedText').value = str;
   //toggleSidebar('viewPinyinizer', true);
   //alert(sidebar.contentDocument.firstChild.id);
   //ta = document.getElementById('pinyinizedText');
   //ta.value = str;
/*alert("in!");
   var result = xrequest.responseText;
   var str = "";
   var tabs = document.getElementsByTagName('table');

   for (var x = 0; x < tabs.length; x = x + 1)
   {
	if (tabs[x].rows[0].cells[0].innerHTML.indexOf("span") == -1)
	str = str + tabs[x].rows[0].cells[0].innerHTML + " "
   }

   var element = document.createElement("div");
   element.setAttribute("class", "dragme");
   element.setAttribute("style", "width:200px;border:1px solid #000;position:absolute;top:20px;left:40px;background-color:white");
   element.innerHTML = str;
   document.childNodes[0].appendChild(element);*/
}
